package app.dbunit;

import org.dbunit.database.IDatabaseConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.SQLException;

public class QuotedNameUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(QuotedNameUtils.class);
    private static final String DOT_MARK = ".";

    public static String getQuotedName(IDatabaseConnection connection, String name) {
        try {
            String qs = connection.getConnection().getMetaData().getIdentifierQuoteString();
            if (qs == null)
                qs = "";
            qs = qs.trim();
            if (qs.isEmpty())
                return name;

            String[] parts = name.split("\\.");
            StringBuilder sb = new StringBuilder();
            for (int i = 0, length = parts.length; i < length; i++) {
                String part = parts[i];
                if (i != 0)
                    sb.append(DOT_MARK);
                if (!part.startsWith(qs))
                    sb.append(qs).append(part).append(qs);
            }
            return sb.toString();
        } catch (SQLException e) {
            LOGGER.warn(e.getMessage(), e);
            return name;
        }
    }

}
